<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 点击新增员工，弹出 -->
      <addEemployee :show-dialog.sync="showDialog" @addEmployee="addEmployee" />
      <!-- 点击角色，弹出 -->
      <authority :id="authorityID" ref="authority" :authority-show.sync="authorityShow" />
      <toolBar :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="addEemployee"> 新增员工</el-button>
        </template>
      </toolBar>
      <!-- 二维码弹出层 -->
      <el-dialog
        title="二维码"
        :visible="QRCodeShow"
        @close="QRCodeShow=false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="staffList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="85">
            <template #default="{row}">
              <div class="via" @click="QRCode(row.staffPhoto)">
                <img v-imgerr="require('@/assets/common/yashi.jpg')" :src="row.staffPhoto" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatFormEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">{{ row.timeOfEntry | formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch :value="row.enableState!==1" />
            </template>
          </el-table-column>

          <el-table-column label="操作" sortable="" fixed="right" width="280" prop="username">
            <template #default="scoped">
              <el-button type="text" size="small" @click="$router.push(`/employees/details/${scoped.row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="authority(scoped.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="sizes,prev, pager, next,jumper" :page-size="page.size" :total="page.total" :page-sizes="[5,10,15,20]" @current-change="currentChange" @size-change="sizeChange" />
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import authority from './components/authority.vue'
import QRCode from 'qrcode'
import { formatDate } from '@/utils/filters/index'
import EnumEmployee from '@/api/constant/employees'
import addEemployee from './components/addEemployee.vue'
import { getStaffList, delEmployee } from '@/api/employees'
// import UploadExcel from '@/components/UploadExcel/index.vue'
// import toolBar from '@/components/toolBar/index.vue'
export default {
  components: {
    addEemployee,
    authority
  },
  data() {
    return {
      authorityID: '',
      authorityShow: false,
      QRCodeShow: false,
      showDialog: false,
      loading: false,
      staffList: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      }
    }
  },
  mounted() {
    // 钩子函数
    this.getStaffList()
  },
  methods: {
    // 角色的点击
    authority(id) {
      this.authorityID = id
      this.$refs.authority.getUserDetailById(id)
      this.authorityShow = true
    },
    // 二维码
    QRCode(url) {
      if (url) {
        this.QRCodeShow = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            color: {
              dark: '#4d7efc', // Blue dots
              light: '#eee' // Transparent background
            }
          })
        })
      }
    },
    // 弹出层里面点击确定，子传父事件
    addEmployee() {
      this.getStaffList()
    },
    // 点击新增员工按钮
    addEemployee() {
      this.showDialog = true
    },
    // 点击 导出 按钮
    async exportExcel() {
      const { export_json_to_excel } = await import('@/views/vendor/Export2Excel')
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '性别'],
      //   data: [
      //     ['王大锤', 30, '男'],
      //     ['小美', 34, '女'],
      //     ['孔连顺', 30, '？']
      //   ]
      // })
      const { rows } = await getStaffList({ page: 1, size: this.page.total })
      // 字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      const data = rows.map(user => {
        return this.obj2arr(user, dict)
      })
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(user, dict) {
      const arr = []
      for (const k in dict) {
        const enKey = dict[k]
        let value = user[enKey]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        } else if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => item.id === Number(value))
          value = obj ? obj.value : '未知形式'
        }
        arr.push(value)
      }
      return arr
    },
    // 使用枚举处理 聘用形式 格式
    formatFormEmployment(row, col, cellValue) {
      const obj = EnumEmployee.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知形式'
    },
    // 点击删除按钮
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除吗?', '提示')
        await delEmployee(id)
        this.$message.success('删除成功')
        if (this.staffList.length === 1) this.page.page--
        this.getStaffList()
      } catch (error) {
        console.log(error)
      }
    },
    // 封装获取员工列表数据函数
    async getStaffList() {
      this.loading = true
      const { rows, total } = await getStaffList(this.page)
      this.staffList = rows
      // this.staffList.forEach(v => {
      //   if (v.timeOfEntry) v.timeOfEntry = v.timeOfEntry.slice(0, 10) + ' ' + v.timeOfEntry.slice(11, 19)
      //   v.formOfEmployment = v.formOfEmployment === 1 ? '正式工' : '临时工'
      //   v.enableState = v.enableState === 1 ? '正常' : '异常'
      // })

      this.page.total = total
      this.loading = false
    },
    // 页码每次变化的事件
    currentChange(newPage) {
      this.page.page = newPage
      this.getStaffList()
    },
    // 页面显示条数变化的事件
    sizeChange(newSize) {
      this.page.size = newSize
      this.getStaffList()
    }
  }
}
</script>
<style  scoped>
.via{
  width: 65px;
  height: 55px;
  text-align: center;
  border-radius: 50%;
  overflow: hidden;
}
.via>img {
  width: 100%;
  height: 100%;
}
</style>
